package net.zoneland.greenleaf.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.zoneland.greenleaf.common.pagination.Pagination;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("ehcache")
public class EhcacheController extends BaseController{
	/**
	 * 如果需要系统对此Controller的访问进行监控，记录服务访问的时间，耗时，那么请将monitor属性设置为“true”
	 */
	public boolean monitor = false;
	
	public static Logger logger = Logger.getLogger(EhcacheController.class);
	
	//通过分析匿名类名称获取当前类名  
	@SuppressWarnings("unused")
	private String clazzName = new Object() {  
        public String getClassName() {  
            String clazzName = this.getClass().getName();  
            return clazzName.substring(0, clazzName.lastIndexOf('$'));  
        }  
    }.getClassName();
    
	@RequestMapping(value = "rss/getCacheList")
	@ResponseBody
	public Object getCacheList() {
		Map<String, Object>map=new HashMap<String,Object>();	
		try{
			CacheManager manager = CacheManager.getInstance();
			String[] cacheNames = manager.getCacheNames();
			map.put("result", "success");
			map.put("data", cacheNames);
			map.put("message", "数据查询成功 ！");
		}catch(Exception e){
			map.put("result", "error");
			map.put("message", "数据查询出错，请联系管理员！");
		}
		return map;
	}
	
	@RequestMapping(value = "rss/getCacheDetail")
	@ResponseBody
	public Object getCacheDetail(String cacheName, int currentPage, int pageSize) {
		Map<String, Object>map=new HashMap<String,Object>();	
		try{
			CacheManager manager = CacheManager.getInstance();
			Cache cache = manager.getCache(cacheName);
			Long hitcount = cache.getStatistics().cacheHitCount();// 获取缓存命中次数
			double hitratio = cache.getStatistics().cacheHitRatio();// 获取磁盘缓存数量
			List<?> keylist = cache.getKeysWithExpiryCheck();
			int size = cache.getKeysWithExpiryCheck().size(); // 获取缓存中元素的个数
			List<Element> elements = new ArrayList<Element>();
			Element e = null;
			if (currentPage == 0) {
				currentPage = 1;
			}
			if (pageSize == 0) {
				pageSize = 10;
			}
			Pagination<?> pagination = Pagination.newPagination(pageSize, currentPage + "", size);
			for (int i = 0; i < keylist.size(); i++) {
				if (i >= pagination.getStartRow()-1) {
					if (i > pagination.getEndRow() -1) {
						// 结束查询
						break;
					}
					// 开始添加到集合里
					e = cache.getQuiet( keylist.get(i) ); // 获取元素（不走统计）
					elements.add(e);
				}
			}
			map.put("pagination", pagination);
			map.put("result", "success");
			map.put("hitratio", hitratio);
			map.put("cacheName", cacheName);
			map.put("size", size);
			map.put("hitcount", hitcount);
			map.put("elements", elements);
			map.put("message", "数据查询成功 ！");
		}catch(Exception e){
			map.put("result", "error");
			map.put("message", "数据查询出错，请联系管理员！");
		}
		return map;
	}
	
	@RequestMapping(value = "cacheDelete")
	@ResponseBody
	public Object cacheDelete(String cacheName, String handel, String key) {
		Map<String, Object>map=new HashMap<String,Object>();	
		try{
			CacheManager manager=CacheManager.getInstance();
			if("deleteByKey".equals(handel)){
				if (cacheName != null && key != null) {
					Cache cache = manager.getCache(cacheName);
					if (cache != null && cache.isKeyInCache(key)) {
						cache.removeQuiet(key);
					}
				}
			}else if("deleteAll".equals(handel)){
			   Cache cache = manager.getCache(cacheName);
			   if(cache != null){
			       cache.removeAll();
			   }
			}
			map.put("result", "success");
			map.put("message", "缓存数据删除成功 ！");
		}catch(Exception e){
			map.put("result", "error");
			map.put("message", "数据查询出错，请联系管理员！");
		}
		return map;
	}
}
